import CircleState from "@/components/CircleState"
import { useIntl, useModel } from "@umijs/max"
import { App, Button, Card, Input, Row, Select, Table } from "antd"
import React, { useEffect, useMemo, useState } from "react"
import CimMessageModal from "./CimMessageModal"
import EapParamsForm from "./EapParamsForm"
// import EapParamsForm from './hdForms/EapParamsForm';
// import DownRecipeForm from './hdForms/DownRecipeForm';

const EapSocket: React.FC = () => {
  const intl = useIntl()
  // 假设 esModel 里有所有需要的状态
  const { eapOnline, dataJsonSend, dataJsonReceive, dataParseResult, eapOrders } =
    useModel("eapModel")

  const { callPy } = useModel("websocketModel")
  const { message } = App.useApp()
  const [requestOptionVal, setRequestOptionVal] = useState("AreYouThereRequest")
  const [userNoInput, setUserNoInput] = useState<string>("")
  const [workType, setWorkType] = useState<"登入" | "登出">("登入") // 1: 登入, 2: 登出
  const [currentUserNo, setCurrentUserNo] = useState<string>("")
  const reqSelectOpList = [
    "AreYouThereRequest",
    "InitialDataRequest",
    "EquipmentCurrentDateTime",
    "EquipmentTotalCount",
    "EquipmentStatus",
    "EquipmentInformation",
    "AlarmWarningDataReport",
    "ProcessDataReport",
    "UserLoginLogoutReport",
    "FilePathAndParameterRequest",
    "CIMMessageCommand"
  ]

  const handleRequestChange = (val: string) => {
    setRequestOptionVal(val)
  }

  const handleMockRequest = async () => {
    const response = await callPy("mr", "mock_request_from_web", [requestOptionVal])
    if (response.state) {
      message.success("模拟请求成功")
    } else {
      message.error("模拟请求失败:" + response.info)
    }
  }

  const handleUserLoginLogout = async () => {
    if (!userNoInput) {
      message.error("请输入 user_no")
      return
    }
    const response = await callPy("eapHandler", "user_login_logout_from_web", [
      workType,
      userNoInput
    ])
    if (response.state) {
      if (workType === "登入") {
        message.success("登入成功")
        setCurrentUserNo(userNoInput)
      } else {
        message.success("登出成功")
        setCurrentUserNo("")
      }
    } else {
      message.error(`操作失败: ${response.info}`)
    }
    // 这里再调用一次获取Eap参数的接口,更新一下当前的user_no
    const response2 = await callPy("ec", "get_eap_params_from_web", [])
    if (response2.state) {
      setCurrentUserNo(response2.data.user_no)
    } else {
      message.error("获取Eap参数失败:" + response2.info)
    }
  }

  const containerStyle = { display: "flex", marginTop: 50, marginLeft: 230 }
  const cardStyleLeft = { flex: "0 0 21%", marginRight: "10px", height: "800px" }
  const cardStyleRight = { flex: "0 0 79%" }
  const textAreaStyle: React.CSSProperties = {
    width: "100%",
    height: "350px",
    fontSize: "14px",
    overflowY: "auto", // 这里用字面量
    padding: "5px",
    marginTop: "5px",
    marginBottom: "5px",
    border: "1px solid #ccc",
    borderRadius: "4px",
    whiteSpace: "pre-wrap"
  }

  const orderColumns = [
    { title: "任务编号", dataIndex: "taskId", key: "taskId", width: 100 },
    { title: "Recipe Name", dataIndex: "recipe_name", key: "recipe_name" },
    { title: "Lot ID", dataIndex: "lot_id", key: "lot_id" },
    { title: "PN ID", dataIndex: "pn_id", key: "pn_id" },
    { title: "板子数量", dataIndex: "panel_count", key: "panel_count", width: 110 },
    { title: "高度", dataIndex: "height", key: "height", width: 90 },
    { title: "宽度", dataIndex: "width", key: "width", width: 90 },
    { title: "创建时间", dataIndex: "created_at", key: "created_at", width: 180 }
  ]

  const orderDataSource = useMemo(
    () =>
      (eapOrders || []).map((item: any, index: number) => ({
        key: item.taskId ?? index,
        ...item
      })),
    [eapOrders]
  )

  useEffect(() => {
    callPy("eapHandler", "get_eap_orders_from_web", [])
  }, [callPy])

  return (
    <div style={containerStyle}>
      <Card style={cardStyleLeft}>
        <span style={{ color: "green", fontWeight: "bold", fontSize: 18 }}>Send</span>
        <div style={textAreaStyle}>{JSON.stringify(dataJsonSend, null, 4)}</div>
        <span style={{ color: "green", fontWeight: "bold", fontSize: 18 }}>Receive</span>
        <div style={textAreaStyle}>{JSON.stringify(dataJsonReceive, null, 4)}</div>
      </Card>

      <Card style={cardStyleRight}>
        <Row align="middle" style={{ marginBottom: 16 }}>
          <span
            style={{ color: "green", fontWeight: "bold", fontSize: 18, marginRight: 10 }}
          >
            Eap状态:
          </span>
          {eapOnline ? (
            <span style={{ alignItems: "center", marginLeft: "10px" }}>
              <CircleState color="green" size={16} />
            </span>
          ) : (
            <CircleState color="red" size={16} />
          )}
          <Select
            style={{ width: 200, marginLeft: 20 }}
            value={requestOptionVal}
            onChange={handleRequestChange}
            options={reqSelectOpList.map((item) => ({ value: item, label: item }))}
          />
          <Button style={{ marginLeft: 10 }} onClick={handleMockRequest}>
            模拟请求
          </Button>
          <span
            style={{ color: "green", fontWeight: "bold", fontSize: 16, marginLeft: 20 }}
          >
            Success
          </span>
          <Input
            value={dataParseResult[0]}
            style={{ marginLeft: 5, width: 80 }}
            disabled
          />
          <span
            style={{ color: "green", fontWeight: "bold", fontSize: 16, marginLeft: 20 }}
          >
            Message
          </span>
          <Input
            value={dataParseResult[1]}
            style={{ marginLeft: 5, width: 150 }}
            disabled
          />
          <span
            style={{ color: "green", fontWeight: "bold", fontSize: 16, marginLeft: 20 }}
          >
            Details
          </span>
          <Input
            value={dataParseResult[2]}
            style={{ marginLeft: 5, width: 250 }}
            disabled
          />
        </Row>
        <Row>
          <span style={{ color: "green", fontWeight: "bold", fontSize: 16 }}>Result</span>
          {/* 换行显示json对象 */}
          <div style={{ width: "100%", margin: "8px 0 0 0" }}>
            <pre
              style={{
                background: "#f6f6f6",
                border: "1px solid #ccc",
                borderRadius: "4px",
                padding: "8px",
                fontSize: "14px",
                whiteSpace: "pre-wrap",
                wordBreak: "break-all",
                margin: 0
              }}
            >
              {dataParseResult[3] ? JSON.stringify(dataParseResult[3], null, 2) : ""}
            </pre>
          </div>
        </Row>
        <hr style={{ border: "1px solid #ccc", margin: "15px 0" }} />
        <Row align="middle" style={{ marginBottom: 8 }}>
          <span
            style={{ color: "green", fontWeight: "bold", fontSize: 18, marginRight: 12 }}
          >
            EAP参数配置
          </span>
          <span style={{ marginRight: 8 }}>输入 user_no:</span>
          <Input
            style={{ width: 140, marginRight: 8 }}
            value={userNoInput}
            onChange={(e) => setUserNoInput(e.target.value)}
            placeholder="请输入工号"
          />
          <Select
            style={{ width: 100, marginRight: 8 }}
            value={workType}
            onChange={(val: "登入" | "登出") => setWorkType(val)}
            options={[
              { value: "登入", label: "登入" },
              { value: "登出", label: "登出" }
            ]}
          />
          <Button type="primary" onClick={handleUserLoginLogout}>
            上下岗
          </Button>
          <span style={{ marginLeft: 16, marginRight: 4 }}>当前登录的 user_no:</span>
          <span style={{ fontWeight: "bold" }}>{currentUserNo || "-"}</span>
        </Row>
        <EapParamsForm />
        <hr style={{ border: "1px solid #ccc", margin: "15px 0" }} />
        <Row style={{ marginBottom: 10 }}>
          <span style={{ color: "green", fontWeight: "bold", fontSize: 18 }}>
            Eap下发任务列表
          </span>
        </Row>
        <Table
          columns={orderColumns}
          dataSource={orderDataSource}
          pagination={false}
          size="small"
          bordered
          scroll={{ x: true }}
        />
      </Card>
      <CimMessageModal />
    </div>
  )
}

export default () => (
  <App>
    <EapSocket />
  </App>
)
